package com.css.zfzx.sjcj.modules.hddcRock5Pre.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.repository.HddcRock5preNativeRepository;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.repository.HddcRock5preRepository;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.repository.entity.HddcRock5preEntity;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.service.HddcRock5preService;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.viewobjects.HddcRock5preQueryParams;
import com.css.zfzx.sjcj.modules.hddcRock5Pre.viewobjects.HddcRock5preVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author lhl
 * @date 2020-11-27
 */
@Service
public class HddcRock5preServiceImpl implements HddcRock5preService {

	@Autowired
    private HddcRock5preRepository hddcRock5preRepository;
    @Autowired
    private HddcRock5preNativeRepository hddcRock5preNativeRepository;

    @Override
    public JSONObject queryHddcRock5pres(HddcRock5preQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcRock5preEntity> hddcRock5prePage = this.hddcRock5preNativeRepository.queryHddcRock5pres(queryParams, curPage, pageSize, sort, order);
        List<HddcRock5preVO> hddcRock5preVOList = new ArrayList<>();
        List<HddcRock5preEntity> hddcRock5preEntityList = hddcRock5prePage.getContent();
        for(HddcRock5preEntity hddcRock5preEntity : hddcRock5preEntityList){
            HddcRock5preVO hddcRock5preVO = new HddcRock5preVO();
            BeanUtils.copyProperties(hddcRock5preEntity, hddcRock5preVO);
            if(PlatformObjectUtils.isNotEmpty(hddcRock5preEntity.getSymbol())) {
                String dictItemCode=String.valueOf(hddcRock5preEntity.getSymbol());
                hddcRock5preVO.setSymbolName(findByDictCodeAndDictItemCode("RockTypeCVD", dictItemCode));
            }
            hddcRock5preVOList.add(hddcRock5preVO);
        }
        Page<HddcRock5preVO> HddcRock5preVOPage = new PageImpl(hddcRock5preVOList, hddcRock5prePage.getPageable(), hddcRock5prePage.getTotalElements());
        JSONObject jsonObject = PlatformPageUtils.formatPageData(HddcRock5preVOPage);
        return jsonObject;
    }


    @Override
    public HddcRock5preEntity getHddcRock5pre(String id) {
        HddcRock5preEntity hddcRock5pre = this.hddcRock5preRepository.findById(id).orElse(null);
         return hddcRock5pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock5preEntity saveHddcRock5pre(HddcRock5preEntity hddcRock5pre) {
        String uuid = UUIDGenerator.getUUID();
        hddcRock5pre.setUuid(uuid);
        hddcRock5pre.setCreateUser(PlatformSessionUtils.getUserId());
        hddcRock5pre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcRock5pre.setIsValid("1");
        hddcRock5pre.setQualityinspectionStatus("0");
        hddcRock5pre.setExtends10("1");
        this.hddcRock5preRepository.save(hddcRock5pre);
        return hddcRock5pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Iterable<HddcRock5preEntity> saveHddcRock5preList(List<HddcRock5preEntity> list) {
        for (HddcRock5preEntity hddcRock5pre : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcRock5pre.setUuid(uuid);
            hddcRock5pre.setCreateUser(PlatformSessionUtils.getUserId());
            hddcRock5pre.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcRock5pre.setIsValid("1");
            hddcRock5pre.setQualityinspectionStatus("0");
            hddcRock5pre.setExtends10("1");
        }

        return hddcRock5preNativeRepository.batchSave(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcRock5preEntity updateHddcRock5pre(HddcRock5preEntity hddcRock5pre) {
        HddcRock5preEntity entity = hddcRock5preRepository.findById(hddcRock5pre.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcRock5pre);
        hddcRock5pre.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcRock5pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcRock5preRepository.save(hddcRock5pre);
        return hddcRock5pre;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcRock5pres(List<String> ids) {
        List<HddcRock5preEntity> hddcRock5preList = this.hddcRock5preRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcRock5preList) && hddcRock5preList.size() > 0) {
            for(HddcRock5preEntity hddcRock5pre : hddcRock5preList) {
                hddcRock5pre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRock5pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRock5pre.setIsValid("0");
                this.hddcRock5preRepository.save(hddcRock5pre);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    public void exportFile(HddcRock5preQueryParams queryParams, HttpServletResponse response) {
        List<HddcRock5preEntity> yhDisasterEntities = hddcRock5preNativeRepository.exportYhDisasters(queryParams);
        List<HddcRock5preVO> list=new ArrayList<>();
        for (HddcRock5preEntity entity:yhDisasterEntities) {
            HddcRock5preVO yhDisasterVO=new HddcRock5preVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"1：5万工作底图岩体-面","1：5万工作底图岩体-面",HddcRock5preVO.class,"1：5万工作底图岩体-面.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcRock5preVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcRock5preVO.class, params);
            List<HddcRock5preVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcRock5preVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcRock5preVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcRock5preEntity> hddcRock5preList = this.hddcRock5preRepository.queryHddcRock5presByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcRock5preList) && hddcRock5preList.size() > 0) {
            for(HddcRock5preEntity hddcRock5pre : hddcRock5preList) {
                hddcRock5pre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRock5pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRock5pre.setIsValid("0");
                this.hddcRock5preRepository.save(hddcRock5pre);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcRock5preEntity> hddcRock5preList = this.hddcRock5preRepository.queryHddcRock5presByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcRock5preList) && hddcRock5preList.size() > 0) {
            for(HddcRock5preEntity hddcRock5pre : hddcRock5preList) {
                hddcRock5pre.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcRock5pre.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcRock5pre.setIsValid("0");
                this.hddcRock5preRepository.save(hddcRock5pre);
            }
        }
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("RockName")){
            str+="RockName,";
        }
        if(!set.contains("Symbol")){
            str+="Symbol,";
        }
        if(!set.contains("QDHO")){
            str+="QDHO,";
        }
        if(!set.contains("Description")){
            str+="Description,";
        }
        if(!set.contains("RockUnion")){
            str+="RockUnion,";
        }
        if(!set.contains("nsb1")){
            str+="nsb1,";
        }
        if(!set.contains("nsb2")){
            str+="nsb2,";
        }
        if(!set.contains("nsb3")){
            str+="nsb3,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public void saveRock5preServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcRock5preEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcRock5preEntity data = new HddcRock5preEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setRockname(obs.get(2).toString());
                data.setSymbol(Integer.valueOf(obs.get(3).toString()));
                data.setQdho(Integer.valueOf(obs.get(4).toString()));
                data.setDescription(obs.get(5).toString());
                data.setRockunion(obs.get(6).toString());
                data.setNsb1(obs.get(7).toString());
                data.setNsb2(obs.get(8).toString());
                data.setNsb3(obs.get(9).toString());
                data.setCommentInfo(obs.get(10).toString());
                data.setExtends16("CGCS2000");
                String pstr=obs.get(0).toString();
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
                /*for(int j=0;j<obs.size();j++){
                    Object value=obs.
                }*/
            }
            deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcRock5preList(datas);
        }
    }

    @Override
    public List<HddcRock5preEntity> findAll() {
        List<HddcRock5preEntity> list=this.hddcRock5preRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();
        hddcRock5preRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    public void deleteByCreateUser(String provinceName,String cityName,String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcRock5preEntity> hddcRock5preList = this.hddcRock5preRepository.queryHddcRock5presByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcRock5preList) && hddcRock5preList.size() > 0) {
            hddcRock5preRepository.deleteAll(hddcRock5preList);
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcRock5preVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcRock5preEntity yhDisasterEntity = new HddcRock5preEntity();
            HddcRock5preVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcRock5pre(yhDisasterEntity);
        }
    }
}
